package logic

import (
	"cloud-disk/core/define"
	"cloud-disk/core/helper"
	"cloud-disk/core/internal/svc"
	"cloud-disk/core/internal/types"
	"cloud-disk/core/models"
	"context"
	"errors"
	"github.com/zeromicro/go-zero/core/logx"
	"time"
)

type MailCodeSendRegisterLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewMailCodeSendRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *MailCodeSendRegisterLogic {
	return &MailCodeSendRegisterLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *MailCodeSendRegisterLogic) MailCodeSendRegister(req *types.MailCodeSendRequest) (resp *types.MailCodeSendReply, err error) {
	// 先判断该邮箱是否被注册
	cnt, err := l.svcCtx.Engine.Where("email = ?", req.Email).Count(new(models.UserBasic))
	if err != nil {
		return nil, err
	}
	if cnt > 0 {
		err = errors.New("该邮箱已被注册")
		return nil, err
	}
	// 获取验证码
	code := helper.RandCode()
	// 将验证码存到redis中
	suc := l.svcCtx.RDB.SetNX(l.ctx, req.Email, code, time.Second*time.Duration(define.CodeExpire))
	// 当前待注册用户的验证码没有过期就不能发送(类似分布式锁)
	if suc.Val() {
		// 发送验证码
		err = helper.MailCodeSend(req.Email, code)
		if err != nil {
			return nil, err
		}
		return resp, nil
	} else {
		return nil, errors.New("验证码发送太频繁，请稍后再试")
	}
}
